import { Model, DataTypes, Optional } from 'sequelize';
import { sequelize } from '../../config/database';
import LiveSession from './LiveSession';

// 统计数据接口
interface StatisticAttributes {
  id: string;
  sessionId: string;
  audienceCount: number;
  createdAt?: Date;
}

// 创建时可选的属性
interface StatisticCreationAttributes extends Optional<StatisticAttributes, 'id' | 'createdAt'> {}

// 统计数据模型类
class Statistic extends Model<StatisticAttributes, StatisticCreationAttributes> implements StatisticAttributes {
  declare id: string;
  declare sessionId: string;
  declare audienceCount: number;
  
  // 时间戳
  declare readonly createdAt: Date;
}

// 初始化模型
Statistic.init(
  {
    id: {
      type: DataTypes.STRING,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    sessionId: {
      type: DataTypes.STRING,
      allowNull: false,
      references: {
        model: LiveSession,
        key: 'id'
      }
    },
    audienceCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0
    }
  },
  {
    sequelize,
    tableName: 'statistics',
    modelName: 'Statistic',
    timestamps: true,
    updatedAt: false,
    indexes: [
      {
        fields: ['sessionId', 'createdAt']
      },
      {
        fields: ['createdAt']
      }
    ]
  }
);

// 设置关联关系
Statistic.belongsTo(LiveSession, { foreignKey: 'sessionId', as: 'session', constraints: false });
LiveSession.hasMany(Statistic, { foreignKey: 'sessionId', as: 'statistics', constraints: false });

export default Statistic;